<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userList" style="width: 100%" border fit>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="名称"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeUserState(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="openEditUser(scope.row)"
              >修改</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="openDelUser(scope.row.id)"
              >删除</el-button
            >
            <el-button type="text" size="small" @click="setRole(scope.row)"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的el-dialog -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="clearForm"
    >
      <!-- 添加用户的表单域 -->
      <el-form
        :model="newUserForm"
        :rules="newUserRules"
        ref="newUserRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="newUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="newUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUser">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的el-dialog -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editUserForm"
        :rules="newUserRules"
        ref="editUserRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUser">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的el-dialog -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleDialogVisible"
      width="50%"
      @close="clearSetRoleForm"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sureSetRole">确 定</el-button>
        <el-button @click="roleDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法邮箱"));
    };
    // 验证手机号
    var checkPhone = (rule, value, callback) => {
      const regPhone =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regPhone.test(value)) {
        return callback();
      }
      callback(new Error("请输入正确的手机号"));
    };

    return {
      // 获取用户列表的参数
      queryInfo: {
        query: "",
        // 当前的页数
        pagenum: 1,
        pagesize: 2,
      },
      // 添加用户
      newUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 修改的表单
      editUserForm: {},
      newUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在3到10个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在6到15个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
      },
      userList: [],
      total: 0,
      dialogVisible: false,
      editDialogVisible: false,
      roleDialogVisible: false,
      // 分配角色的用户信息
      userInfo: {},
      // 分配角色的角色列表
      roleList: [],
      // 分配角色->分配新角色中所拿到的值
      value: "",
    };
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取管理员列表失败");
      }
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // pagesize改变触发的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 改变用户状态
    async changeUserState(e) {
      const { data: res } = await this.$http.put(
        `users/${e.id}/state/${e.mg_state}`
      );
      if (res.meta.status !== 200) {
        e.mg_state = !e.mg_state;
        return this.$message.error("改变用户状态失败");
      }
      return this.$message.success("设置状态成功");
    },
    // 关闭dialog时清空内容
    clearForm() {
      this.$refs.newUserRef.resetFields();
    },
    // 确定后添加用户
    addUser() {
      this.$refs.newUserRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.newUserForm);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败");
        } else {
          this.$message.success("添加用户成功");
          this.getUserList();
          this.dialogVisible = false;
        }
      });
    },
    // 打开修改用户dialog的方法
    openEditUser(userInfo) {
      this.editUserForm = userInfo;
      this.editDialogVisible = true;
    },
    // 修改用户的方法
    editUser() {
      this.$refs.editUserRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "users/" + this.editUserForm.id,
          { email: this.editUserForm.email, mobile: this.editUserForm.mobile }
        );
        if (res.meta.status !== 200) {
          this.$message.error("修改用户失败");
        } else {
          this.$message.success("修改用户成功");
          this.getUserList();
          this.editDialogVisible = false;
        }
      });
    },
    // 打开删除用户dialog的方法
    openDelUser(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "删除用户", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("users/" + id);
          if (res.meta.status !== 200) {
            return this.$message.error("删除用户失败");
          }
          this.getUserList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 分配角色
    async setRole(info) {
      this.userInfo = info;
      // 在展示对话框前获得所有角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.roleList = res.data;
      this.roleDialogVisible = true;
    },
    // 确认分配角色
    async sureSetRole() {
      if (!this.value) {
        return this.$message.error("请选择要分配的角色");
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        { id: this.userInfo.id, rid: this.value }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("设置角色失败");
      }
      this.$message.success("设置角色成功");
      this.getUserList();
      this.roleDialogVisible = false;
    },
    // 分配角色dialog关闭后清楚数据
    clearSetRoleForm() {
      this.value = "";
      this.userInfo = {};
    },
  },
  created() {
    this.getUserList();
  },
};
</script>

<style lang="less" scoped>
</style>